﻿Imports SaveConverterNDS
Imports SaveFormatInterface
Imports SaveFormatInterface.Interfaces
Imports System.IO
Imports System.Text
Class MainWindow
    Dim opath As String
    Dim spath As String
    Dim dpath As String
    Public Property SelectedFiles As New Generic.List(Of ConversionOption)
    Private Sub btnClose_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnClose.Click
        Me.Close()
    End Sub

    Private Sub Window_Loaded(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles MyBase.Loaded
        reload()
    End Sub
    Sub reload()
        Dim d As New Save_Type_Dialog
        Dim formats As Generic.List(Of Interfaces.SaveFormat) = SaveConverterNDS.Converter.GetSaveFormats(d.GetFormatType)
        Dim x As New ToStringComparer(Of SaveFormat)
        formats.Sort(1, formats.Count - 1, x)
        'Dim formatlist(formats.Count - 1) As String
        'For count As Integer = 0 To formats.Count - 1
        '    formatlist(count) = formats(count).FriendlyName
        'Next
        'Array.Sort(formatlist, 1, formatlist.Length - 1)
        For Each item In formats
            If item.CanBeSource Then cbSource.Items.Add(item)
            If item.CanBeTarget Then cbTarget.Items.Add(item)
        Next
        For Each item In SaveConverterNDS.SizeManager.SizeArray
            cbSize.Items.Add(item)
        Next
        cbSource.SelectedIndex = 0
        cbTarget.SelectedIndex = 0
        'cbSize.SelectedIndex = 0 ' Done with cbTarget_SelectionChanged
        txtInput.Text = "0 Files Selected."
    End Sub
    Private Function SaveExtension(ByVal Filename As String) As String
        Dim parts() As String = Filename.Split(".")
        If parts.Length = 2 Then
            Return parts(1)
        ElseIf parts.Length < 2 Then
            Return ""
        ElseIf parts(parts.Length - 2).Length = 1 Then
            If IsNumeric(parts(parts.Length - 2)) Then
                Return parts(parts.Length - 2) & "." & parts(parts.Length - 1)
            Else
                Return parts(parts.Length - 1)
            End If
        Else
            Return parts(parts.Length - 1)
        End If
    End Function
    ''' <summary>
    ''' Returns the game code of an NDS ROM at the specified location.  Ex. US Super Mario 64 DS returns ASME
    ''' </summary>
    ''' <param name="Filename">Location of the NDS ROM to get the game code from</param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Shared Function GetGameCode(ByVal Filename As String) As String
        Dim input As New FileStream(Filename, FileMode.Open)
        Dim reader As New BinaryReader(input)
        reader.BaseStream.Position = 12
        Dim code As String = Encoding.UTF8.GetString(reader.ReadBytes(4))
        input.Close()
        Return code
    End Function
    Private Sub btnConvert_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnConvert.Click
        Static CurrentDirectory As String = Environment.CurrentDirectory
        Dim SourceFormat As SaveFormat = cbSource.SelectedItem
        Dim TargetFormat As SaveFormat = cbTarget.SelectedItem
        If SelectedFiles.Count = 1 Then
            Dim SaveFileDialog1 As New Microsoft.Win32.SaveFileDialog
            SaveFileDialog1.InitialDirectory = spath
            SourceFormat.IsOnline = False
            SourceFormat.Filename = txtInput.Text
            TargetFormat.IsOnline = False
            TargetFormat.Filename = txtInput.Text
            SaveFileDialog1.Filter = "Target Format (*." & TargetFormat.FileExtension & ")|*." & TargetFormat.FileExtension & "|All Files (*.*)|*.*"

            If SaveFileDialog1.ShowDialog Then
                Dim size As Long
                size = SaveConverterNDS.SizeManager.Size(SaveConverterNDS.SizeManager.SizeArray(cbSize.SelectedIndex))

                Dim output As Byte() = SaveConverterNDS.Converter.Convert(IO.File.ReadAllBytes(txtInput.Text), SourceFormat, TargetFormat, size)
                My.Computer.FileSystem.WriteAllBytes(SaveFileDialog1.FileName, output, False)
                spath = IO.Path.GetDirectoryName(SaveFileDialog1.FileName)
                MessageBox.Show("Conversion Successful!")
            End If
        ElseIf SelectedFiles.Count > 1 Then
            Dim log As String = ""
            Dim TargetDirectory As String = ""
            For Each item In SelectedFiles
                If IO.File.Exists(item.SourceFileName) Then
                    'Find SourceFormat
                    Dim CurrentSourceFormat As SaveFormat
                    If item.SourceFormat Is Nothing Then
                        CurrentSourceFormat = SourceFormat
                    Else
                        CurrentSourceFormat = item.SourceFormat
                    End If
                    'Find TargetFormat
                    Dim CurrentTargetFormat As SaveFormat
                    If item.TargetFormat Is Nothing Then
                        CurrentTargetFormat = TargetFormat
                    Else
                        CurrentTargetFormat = item.TargetFormat
                    End If
                    CurrentTargetFormat.IsOnline = True 'Don't open any dialogs
                    Dim GN As String = ""
                    If String.IsNullOrEmpty(item.ARDSGameName) Then
                        Dim titlefilename As String
                        Dim code As String = ""
                        Dim sav As New IO.FileInfo(item.SourceFileName)
                        Dim ndsfile As String = sav.Directory.FullName & "/" & sav.Name.Replace("." & SaveExtension(sav.Name), "") & ".nds"
                        If IO.File.Exists(ndsfile) Then
                            code = GetGameCode(ndsfile)
                        End If
                        If code = "" Then
                            'Unknown purpose: _filename = sav.Directory.FullName & "/" & sav.Name & ".nds"
                            If IO.File.Exists(ndsfile) Then
                                code = GetGameCode(ndsfile)
                            End If
                        End If
                        If False Then
                            titlefilename = CurrentDirectory & "/gamedb/" & code(3) & "/" & code.Substring(0, 3) & ".txt"
                        Else
                            titlefilename = CurrentDirectory & "/gamedb/" & code & ".txt"
                        End If
                        If Not code = "" AndAlso code.Length = 4 Then
                            If IO.File.Exists(titlefilename) Then
                                GN = IO.File.ReadAllText(titlefilename)
                            End If
                            '_gamecode = code
                            'If IO.File.Exists(Form1.CurrentDirectory & "/ndsnamedb.txt") Then
                            '    Dim m As New Converter.NDSROMManager(Form1.CurrentDirectory & "/ndsnamedb.txt")
                            '    txtGameName.Text = m.GameName(code)
                            'End If
                        End If
                    End If
                    CurrentTargetFormat.ExtendedData = GN.Replace("_", "__").Replace("ÿ", "_y") & "ÿ" & item.ARDSSaveName.Replace("_", "__").Replace("ÿ", "_y") & "ÿ" & item.ARDSDescription.Replace("_", "__").Replace("ÿ", "_y")
                    'Find TargetSize
                    Dim size As Integer
                    If item.TargetSize < 0 Then
                        size = SaveConverterNDS.SizeManager.Size(SaveConverterNDS.SizeManager.SizeArray(cbSize.SelectedIndex))
                    Else
                        size = item.TargetSize
                    End If
                    'Find TargetDirectory
                    Dim CurrentTargetFilename As String
                    If item.TargetFileName = "" Then
                        If TargetDirectory = "" Then
dirDialogBlock:             Dim dirDialog As New System.Windows.Forms.FolderBrowserDialog
                            If Not String.IsNullOrEmpty(dpath) Then
                                dirDialog.SelectedPath = dpath
                            End If
                            dirDialog.ShowNewFolderButton = True
                            If dirDialog.ShowDialog = Forms.DialogResult.OK Then
                                TargetDirectory = dirDialog.SelectedPath
                                dpath = dirDialog.SelectedPath
                            Else
                                If MessageBox.Show("Would you like to cancel this batch operation?", "Offline NDS Save Converter", MessageBoxButton.YesNo) = MessageBoxResult.Yes Then
                                    log += "[" & item.SourceFileName & "] Canceled batch operation" & vbCrLf
                                    Exit For
                                Else
                                    GoTo dirDialogBlock
                                End If
                            End If
                        End If
                        CurrentTargetFilename = IO.Path.Combine(TargetDirectory, IO.Path.GetFileNameWithoutExtension(item.SourceFileName) & "." & TargetFormat.FileExtension)
                    Else
                        CurrentTargetFilename = item.TargetFileName
                    End If
                    Dim output As Byte() = SaveConverterNDS.Converter.Convert(IO.File.ReadAllBytes(item.SourceFileName), CurrentSourceFormat, CurrentTargetFormat, size)
                    My.Computer.FileSystem.WriteAllBytes(CurrentTargetFilename, output, False)
                    log += "[" & item.SourceFileName & "] Converted Successfully"
                Else
                    log += "[" & item.SourceFileName & "] File does not exist" & vbCrLf
                End If
            Next
            MessageBox.Show("Batch conversion completed.")
        Else
            MessageBox.Show("Please select one or more files to be converted.")
        End If
    End Sub
    Private Sub txtInput_MouseUp(ByVal sender As Object, ByVal e As System.Windows.Input.MouseButtonEventArgs) Handles txtInput.MouseUp
        If SelectedFiles.Count > 1 Then
            MessageBox.Show("Set individual properties feature comming soon.")
        End If
    End Sub
    Private Sub txtInput_TextChanged(ByVal sender As System.Object, ByVal e As System.Windows.Controls.TextChangedEventArgs) Handles txtInput.TextChanged
        If SelectedFiles.Count > 1 OrElse (SelectedFiles.Count = 1 AndAlso IO.File.Exists(txtInput.Text)) Then 'IO.File.Exists(txtInput.Text) Then
            Dim a As New Animation.DoubleAnimation()
            'a.From = 0
            a.To = 1
            a.Duration = New Duration(TimeSpan.Parse("0:0:1"))
            btnConvert.BeginAnimation(Button.OpacityProperty, a)
        Else
            Dim a As New Animation.DoubleAnimation()
            'a.From = 1
            a.To = 0
            a.Duration = New Duration(TimeSpan.Parse("0:0:1"))
            btnConvert.BeginAnimation(Button.OpacityProperty, a)
        End If
    End Sub

    Private Sub btnBrowse_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)
        'MessageBox.Show("Multi-select not implemented.  You can only select one file total.")
        Dim OpenFileDialog1 As New Microsoft.Win32.OpenFileDialog
        OpenFileDialog1.InitialDirectory = opath
        OpenFileDialog1.Filter = "All Files (*.*)|*.*"
        OpenFileDialog1.FileName = ""
        OpenFileDialog1.Multiselect = True
        If OpenFileDialog1.ShowDialog Then
            For Each item In OpenFileDialog1.FileNames
                SelectedFiles.Add(New ConversionOption(item, Nothing, Nothing, "", -1, "", "", ""))
            Next
            If SelectedFiles.Count = 1 Then
                txtInput.Text = SelectedFiles(0).SourceFileName
                txtInput.IsReadOnly = False
            Else
                txtInput.Text = String.Format("{0} Files Selected.", SelectedFiles.Count)
                txtInput.IsReadOnly = True
            End If
        End If
        On Error Resume Next
        opath = IO.Path.GetDirectoryName(OpenFileDialog1.FileNames(0))
    End Sub

    Private Sub cbTarget_SelectionChanged(ByVal sender As Object, ByVal e As System.Windows.Controls.SelectionChangedEventArgs) Handles cbTarget.SelectionChanged
        Dim TargetFormat As SaveFormat = cbTarget.SelectedItem
        cbSize.Items.Clear()
        If TargetFormat.FileSize.Length = 0 Then
            For Each item In SaveConverterNDS.SizeManager.SizeArray
                cbSize.Items.Add(item)
            Next
        Else
            For Each item As Long In TargetFormat.FileSize
                cbSize.Items.Add(SaveConverterNDS.SizeManager.GetStringFromInteger(item))
            Next
        End If
        cbSize.SelectedIndex = 0
    End Sub
    Private Sub btnResetSelection_Click(sender As System.Object, e As System.Windows.RoutedEventArgs) Handles btnResetSelection.Click
        SelectedFiles.Clear()
        btnBrowse_Click(sender, e)
    End Sub
End Class
